package org.vidi.amqp.basic;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.vidi.amqp.common.ConnectionUtils;
import org.vidi.amqp.common.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author vidi
 */
public class ProducerBatch {

    public static void main(String[] args) {
        try (Connection connection = ConnectionUtils.newSingleConnection();
             Channel channel = connection.createChannel()) {

            channel.queueDeclare(Constants.PRODUCER_BATCH_QUEUE_NAME, false, false, false, null);
            channel.confirmSelect();

            int batchSize = 100;
            int outstandingMessageCount = 0;
            for (int i = 0; i < Constants.MESSAGE_COUNT; i++) {
                String message = "PublishBatch-" + i;
                channel.basicPublish("", Constants.PRODUCER_BATCH_QUEUE_NAME, null, message.getBytes());
                outstandingMessageCount++;
                if (outstandingMessageCount == batchSize) {
                    channel.waitForConfirmsOrDie(5000);
                    outstandingMessageCount = 0;
                }
            }

            if (outstandingMessageCount > 0) {
                channel.waitForConfirmsOrDie(5000);
            }
            System.out.format("Published %,d messages in batch", Constants.MESSAGE_COUNT);

        } catch (TimeoutException | IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
